package com.yuelan.apartment.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import com.yuelan.common.core.exception.GlobalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @Author: ZhaoYi
 * @date: 24-7-2 18:38
 */

@Configuration
@EnableCaching
public class CacheConfig {

    private final static Logger logger = LoggerFactory.getLogger(GlobalException.class);

    @Bean
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                // 开启记录缓存命中率等信息
                .recordStats()
                .build();
    }

    // 监控缓存的命中率和负载情况
    @Bean
    public void cacheMonitor() {
        CacheStats stats = caffeineCache().stats();
        logger.info(String.valueOf(stats));
    }

}
